import React, { createContext, ReactNode, useContext, useState } from 'react';

export interface SelectedMediaItem {
  id: string;
  url: string;
  type: 'photo' | 'video';
  duration?: number;
  creationTime: number;
  width?: number;
  height?: number;
}

interface MediaSelectionContextType {
  selectedMedia: SelectedMediaItem[];
  setSelectedMedia: (media: SelectedMediaItem[]) => void;
  clearSelection: () => void;
  addMedia: (media: SelectedMediaItem) => void;
  removeMedia: (id: string) => void;
}

const MediaSelectionContext = createContext<MediaSelectionContextType | undefined>(undefined);

export const useMediaSelection = () => {
  const context = useContext(MediaSelectionContext);
  if (!context) {
    throw new Error('useMediaSelection must be used within a MediaSelectionProvider');
  }
  return context;
};

interface MediaSelectionProviderProps {
  children: ReactNode;
}

export const MediaSelectionProvider: React.FC<MediaSelectionProviderProps> = ({ children }) => {
  const [selectedMedia, setSelectedMedia] = useState<SelectedMediaItem[]>([]);

  const clearSelection = () => {
    setSelectedMedia([]);
  };

  const addMedia = (media: SelectedMediaItem) => {
    setSelectedMedia(prev => [...prev, media]);
  };

  const removeMedia = (id: string) => {
    setSelectedMedia(prev => prev.filter(item => item.id !== id));
  };

  return (
    <MediaSelectionContext.Provider
      value={{
        selectedMedia,
        setSelectedMedia,
        clearSelection,
        addMedia,
        removeMedia,
      }}
    >
      {children}
    </MediaSelectionContext.Provider>
  );
};